package com.jc.service.task.productImg;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.jc.framework.util.PropertyPlaceholder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.ImageUtil;
import com.jc.common.util.UrlUtil;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SupplierProduct;
import com.jc.framework.enums.ImageStatus;
import com.jc.framework.enums.Push;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.upload.aliyun.oos.AliyunOssUtil;

@Service
public class ProductImageServiceImpl implements ProductImageService{

    public Logger getLoger() {
        return LoggerFactory.getLogger(this.getClass());
    }

    @Autowired
    private SupplierGoodsPictureListService supplierGoodsPictureListService;
    @Autowired
    private SupplierProductService supplierProductService;
    
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    
    
    
    @Transactional
    @Override
    public void compressionImg() {
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setPushStatus(Push.WAIT_DEAL.getName()); //待处理
        supplierProduct.setIsImgCompression(ImageStatus.UNCOMPRESSED.getName());//未压缩
        //
        supplierProduct.setId(6784L);
        List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProduct);
        supplierProducts.forEach(sup->{
            //查询当前商品的图片 压缩
            SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
            supplierGoodsPictureList.setGid(sup.getGid());
            List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(supplierGoodsPictureList);
            supplierGoodsPictureLists.forEach(supplierGoodsPicture->{
                //判断私有云图片字段是否为空
                if (StringUtils.isBlank(supplierGoodsPicture.getSelfImagePath()) && StringUtils.isNotBlank(supplierGoodsPicture.getImagePath())){
                    String selfImagePath = imageZipUpload(supplierGoodsPicture.getImagePath());
                    SupplierGoodsPictureList upSuppList = new SupplierGoodsPictureList();
                    upSuppList.setId(supplierGoodsPicture.getId());
                    upSuppList.setSelfImagePath(selfImagePath);
                    supplierGoodsPictureListService.modify(upSuppList,false);
                }
            });
            SupplierProduct supPro = new SupplierProduct();
            supPro.setId(sup.getId());
            supPro.setIsImgCompression(ImageStatus.COMPRESSED.getName());
            supPro.setPushStatus(Push.WAIT_PUSH.getName());
            supplierProductService.modify(supPro,false);
        });
    }

    
    
  
    @Override
    public void compressionImgtemp() {
    	int threadCount = 4;
        SupplierProduct supplierProduct = new SupplierProduct();
        
        supplierProduct.setIsImgCompression(ImageStatus.UNCOMPRESSED.getName());//未压缩
        supplierProduct.orderById(true);
        List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProduct);
//        supplierProducts.forEach(sup->{
//        	zipImageUpload(sup);
//        });
        
        for(int i = 0 ; supplierProducts != null && i < supplierProducts.size() ; i++) {
        	SupplierProduct bo = supplierProducts.get(i);
        	int hasCode = bo.hashCode();
        	getLoger().error("HASH NUMBER----------------------------------> : " + hasCode + "  ---------------------->" + hasCode%threadCount);
        	if(hasCode%threadCount==0) {
        		taskExecutor.execute(new Runnable() {
        			@Override
        			public void run() {
        				zipImageUpload(bo);
        			}
        		});
			}
			if(hasCode%threadCount==1) {
				taskExecutor.execute(new Runnable() {
	    			@Override
	    			public void run() {
	    				zipImageUpload(bo);
	    			}
	    		});
			}
			if(hasCode%threadCount==2) {
				taskExecutor.execute(new Runnable() {
	    			@Override
	    			public void run() {
	    				zipImageUpload(bo);
	    			}
	    		});
			}
			if(hasCode%threadCount==3) {
				taskExecutor.execute(new Runnable() {
	    			@Override
	    			public void run() {
	    				zipImageUpload(bo);
	    			}
	    		});
			}
        	
        }
    }
    
    @Transactional
    public void zipImageUpload(SupplierProduct sup) {
    	//查询当前商品的图片 压缩
        SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
        supplierGoodsPictureList.setGid(sup.getGid());
        List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(supplierGoodsPictureList);
        supplierGoodsPictureLists.forEach(supplierGoodsPicture->{
            //判断私有云图片字段是否为空
            if (StringUtils.isBlank(supplierGoodsPicture.getSelfImagePath()) && StringUtils.isNotBlank(supplierGoodsPicture.getImagePath())){
                String selfImagePath = imageZipUpload(supplierGoodsPicture.getImagePath());
                SupplierGoodsPictureList upSuppList = new SupplierGoodsPictureList();
                upSuppList.setId(supplierGoodsPicture.getId());
                upSuppList.setSelfImagePath(selfImagePath);
                supplierGoodsPictureListService.modify(upSuppList,false);
            }
        });
        SupplierProduct supPro = new SupplierProduct();
        supPro.setId(sup.getId());
        supPro.setIsImgCompression(ImageStatus.COMPRESSED.getName());
        //supPro.setPushStatus(Push.WAIT_PUSH.getName());
        supplierProductService.modify(supPro,false);
    }
    
    
    
    public String imageZipUpload(String remoteUrl) {
        String localPath = "/usr/local/static/img/";
        String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
        try {
            String path = localPath + datestr;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            String extName = UrlUtil.getFileExtension(remoteUrl);
            String notZipFilePath = path + "/" + name + "." + extName;
            String zipFilePath = path + "/" + "zip" + name + "." + extName;
            ImageUtil.downloadPicture(remoteUrl, notZipFilePath);
            String localhostPath = "";
            try {
                //获取图片大小
                long imgSize = new File(notZipFilePath).length();
                //获取不压缩图片的大小
                Long compressionSize = Long.valueOf(String.valueOf(PropertyPlaceholder.getProperty("compression.size")));
                if (imgSize <= compressionSize){
                    localhostPath = notZipFilePath;
                }else{
                    localhostPath = ImageUtil.outputQuality(notZipFilePath, 0.5, zipFilePath, new BigDecimal("100"));
                }
            }catch (Exception e) {
            	getLoger().error("压缩图片错误: {},{}",e.getMessage(),e);
			}
            if(StringUtils.isBlank(localhostPath)) {
            	return "";
            }
            // 上传
            File file = new File(localhostPath);
            AliyunOssUtil util = new AliyunOssUtil();
            String imageURL = util.uploadImg2Oss(file);
            //上传完成删除本地服务器图片
            file.delete();
            File notZipFile = new File(notZipFilePath);
            notZipFile.delete();
            getLoger().debug("删除服务器图片:"+localhostPath);
            return imageURL;
        } catch (Exception e) {
            getLoger().error("压缩上传图片出现错误, 图片源地址: {} , 错误原因: {},{}", remoteUrl, e.getMessage(), e);
        }
        return null;
    }


}
